package com.itheima.service.impl;

import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpExpr;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.PageQuery;
import com.itheima.service.EmpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmpServiceImpl implements EmpService {
    private final EmpMapper empMapper;

    private final EmpExprMapper empExprMapper;

    @Override
    public PageBean queryAllByCondition(PageQuery pageQuery) {
        //查询到所有的数据
        Integer total = empMapper.queryAllCount(pageQuery);
        //当前页
        Integer page = pageQuery.getPage();
        //每页大小
        Integer pageSize = pageQuery.getPageSize();

        Integer start = (page - 1) * pageSize;

        List<Emp> emps = empMapper.queryAllByCondition(start, pageSize, pageQuery);

        PageBean pageBean = new PageBean(total, emps);

        return pageBean;
    }

    @Override
    public void addEmp(Emp emp) {
        emp.setCreateTime(LocalDate.now());
        emp.setUpdateTime(LocalDate.now());
        List<EmpExpr> empExprList = emp.getExprList();
        log.info(empExprList.toString());
        empMapper.addEmp(emp);
        if (empExprList != null && !empExprList.isEmpty()) {
            empExprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            empExprMapper.addEmpExpr(emp.getExprList());
        }
    }

    @Override
    public Emp queryEmpById(Integer id) {
        Emp emp = empMapper.queryEmpById(id);
        return emp;
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        empMapper.deleteByIds(ids);
    }

    @Override
    @Transactional
    public void updateEmp(Emp emp) {
        empMapper.updateEmpById(emp);
        List<EmpExpr> exprList = emp.getExprList();
        //empList中有值 删除
        if (!exprList.isEmpty()) {
            empExprMapper.deleteEmpExpr(exprList);
        }

        exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));

        empExprMapper.addEmpExpr(exprList);
    }

}
